package swing;

import javax.swing.*;
import java.awt.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: nuno-rafael-figueiredo
 * Date: 20-02-2014
 * Time: 18:06
 */
public class FormPanel<TItem> extends JPanel {
    /**
	 * 
	 */
	private static final long serialVersionUID = -2284105692267246055L;

    protected final GridPanel gridPanel = new GridPanel();
    protected final JButton defaultButton = new JButton();
    private final Map<String, Component> componentMap = new LinkedHashMap<>();

    public TItem getItem() {
        return item;
    }

    private TItem item;

    public FormPanel(String defaultButtonText) {
        super(new BorderLayout());

        JPanel buttonsPanel = new JPanel();
        add(buttonsPanel, BorderLayout.SOUTH);
        add(gridPanel);

        defaultButton.setText(defaultButtonText);
        buttonsPanel.add(defaultButton);
        if (getRootPane() != null)
            getRootPane().setDefaultButton(defaultButton);
    }

    public <TComponent extends Component> TComponent addField(String label, TComponent component){

        gridPanel.set(0, componentMap.size(), new JLabel(label));
        gridPanel.set(1, componentMap.size(), component);

        componentMap.put(label, component);

        return component;
    }

    public void setItem(TItem item) {
        this.item = item;
    }
}
